package cn.alex.sso.project.controller;

import cn.alex.sso.framework.global.ServiceException;
import cn.alex.sso.project.entity.SysClient;
import cn.alex.sso.project.service.SysClientService;
import cn.dev33.satoken.sso.config.SaSsoClientConfig;
import cn.dev33.satoken.sso.processor.SaSsoClientProcessor;
import cn.hutool.core.util.ObjUtil;
import com.dtflys.forest.Forest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * SSO客户端处理器
 *
 * @author Alex
 * @date 2024/9/24 14:44
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class SsoClientController {
    private final SysClientService clientService;

    @RequestMapping("/sso/client/*")
    public Object ssoRequest() {
        return SaSsoClientProcessor.instance.dister();
    }

    @Autowired
    private void ssoClientConfig(SaSsoClientConfig sso) {
        SaSsoClientProcessor.instance.ssoClientTemplate.apiName.ssoLogin = "/sso/client/login";
        SaSsoClientProcessor.instance.ssoClientTemplate.apiName.ssoLogout = "/sso/client/logout";
        SaSsoClientProcessor.instance.ssoClientTemplate.apiName.ssoLogoutCall = "/sso/client/logoutCall";

        SysClient lcSsoServerClient = clientService.getLcSsoServerClient();
        if (ObjUtil.isEmpty(lcSsoServerClient)) {
            throw new ServiceException("请先配置一个sso服务端");
        }

        sso.setClient(lcSsoServerClient.getId().toString());

        // 配置Http请求处理器
        sso.sendHttp = url -> {
            try {
                return Forest.get(url).executeAsString();
            } catch (Exception e) {
                log.error("请求[{}]失败", url, e);
                return null;
            }
        };
    }
}
